<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Invoice;
use App\Models\Order;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class InvoiceController extends Controller
{
    private $user_id;
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        if (\Auth::guard('api')->check()) {
            $user = \Auth::guard('api')->user();
            $this->user_id = $user->id;
        }
    }
    //新增保存
    public function add(Request $request)
    {
        $validator = \Validator::make($request->all(),
            ['orderId' => 'required', 'title' => 'required|max:255', 'taxesNo' => 'required|max:255', 'name' => 'required|max:20', 'mobile' => 'required|regex:/^[1][0-9]{10}$/','address' => 'required|max:255'],
            ['orderId.required' => '订单id不能为空', 'title.required' => '发票抬头不能为空', 'title.max' => '发票抬头最多255个字符', 'taxesNo.required' => '纳税人识别号不能为空', 'taxesNo.max' => '纳税人识别号最多255个字符', 'name.required' => '姓名不能为空',
                'name.max' => '姓名最多255个字符', 'mobile.required' => '手机号不能为空',
                'mobile.regex' => '手机号格式不正确','address.required' => '收货地址不能为空', 'address.max' => '收货地址最多255个字符']);
        if ($validator->fails()) {
            return response()->json(['code' => 500, 'msg' => $validator->errors()->first()]);
        }
        $orderId = $request->input('orderId');
        $orderInfo = Order::where('id', $orderId)->where('status', 2)->first();
        if (empty($orderInfo)) {
            $return = ['code' => 500, 'msg' => '不存在的订单id！'];
            return response()->json($return);
        }
        $result = Invoice::create([
            'userId' => $this->user_id,
            'orderId' => $orderId,
            'title' => $request->input('title'),
            'taxesNo' => $request->input('taxesNo'),
            'name' => $request->input('name'),
            'mobile' => $request->input('mobile'),
            'address' => $request->input('address'),
        ]);
        if ($result) {
            return $this->respond('add_ok', ['orderInfo' => $orderInfo, 'invoiceInfo' => $result]);
        }
        return $this->respond('add_error');
    }
}
